package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import ${tableClass.fullClassName};
import ${tableClass.fullClassName?replace('sensor','history')};
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.serviceImpl.${tableClass.shortClassName}ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;
import java.text.ParseException;
import java.util.Date;

/*这里beanName需要和数据库Appdevice中的simple对应并加上Com,不对应请自行修改
    例:simple:dlhl
    @Service("dlhlCom")
*/
@Service("${tableClass.shortClassName?uncap_first?replace('sensor','Com')}")
@Scope("prototype")
public class ${tableClass.shortClassName?replace('sensor','Com')} extends CommPortManager {
        @Autowired
        private ${tableClass.shortClassName}ServiceImpl ${tableClass.shortClassName?uncap_first}ServiceImpl;

        @Override
        public void receiveData(String str) {
            try {
                str = str.toUpperCase();
                setText(str);
                //条件判断自己写
                //  todo
                //  todo
                //  todo
                if (str.length()==45&&"7F".equals(str.substring(0, 2)))
                return;
                if(str.length()==45){
                    ${tableClass.shortClassName} ${tableClass.shortClassName?uncap_first} =  new ${tableClass.shortClassName}();
                    AddAndUpdate(${tableClass.shortClassName?uncap_first});
                }else{
                    setText("从设备返回的数据有误！请检查串口！");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                setText("从设备返回的数据有误！请检查串口！");
            }
        }

        @Transactional
        private void AddAndUpdate(${tableClass.shortClassName} record) {
            int alarmLevel = 0;// 报警等级
            String alarmMessage = "";// 报警消息
            //报警逻辑
            //这里写报警逻辑
            //  todo
            //  todo
            //  todo
            record.setLastalarmlevel(alarmLevel);
            record.setLastalarmmessage(alarmMessage);
            record.setLastcommunicationstatus(0);
            record.setLastdatatime(new Date());
            record.setLasthisdatatime(addHistory(${tableClass.shortClassName?uncap_first}ServiceImpl.getModel(record)));
            if ( ${tableClass.shortClassName?uncap_first}ServiceImpl.Update(record, false) == 0) {
                setText("更新实时数据失败，请检查数据库连接");
            }
        }
        private Date addHistory(${tableClass.shortClassName} sensor) {
            if (sensor != null) {
                if (sensor.getLasthisdatatime() == null) {
                    add(sensor);
                    return new Date();
                } else {
                    long lasttime = 0;
                    long nowtime = 0;
                    try {
                        lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                        nowtime = HexUtil.todate(new Date()).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    int timersp = 60000;
                    if (sensor.getLastalarmlevel() != 0) {
                        timersp = ad.getHisalarmtimersp()*1000;
                    } else {
                        timersp = ad.getHistimersp()*1000;
                    }
                    if (lasttime + timersp < nowtime) {
                        add(sensor);
                        return new Date();
                    }
                }
            }
            return null;
        }

        private void add(${tableClass.shortClassName} sensor) {
            ${tableClass.shortClassName?replace('sensor','history')} his = new ${tableClass.shortClassName?replace('sensor','history')}();
            his.setDeviceaddr(sensor.getDeviceaddr());
            his.setDevicegroup(sensor.getDevicegroup());
            his.setAlarmlevel(sensor.getLastalarmlevel());
            his.setAlarmmessage(sensor.getLastalarmmessage());
            his.setDatatime(sensor.getLastdatatime());
            his.setPointname(sensor.getPointname());
            his.setStationid(sensor.getStationid());
            //需要添加自己定义的属性
            //  todo
            ${tableClass.shortClassName?uncap_first}ServiceImpl.Add(his);
        }


        @Async("threadPool")
        public void startSendThread(Appdevice Appdevice) throws Exception {
            setText("正在尝试打开" + Appdevice.getName() + "串口...");
            Open();
            setText("端口" + Appdevice.getCom() + "打开成功");
            issend.put(Thread.currentThread().getId(), true);
            String cstr = "";
            String cmdtype = "";
            String nametype = "";
            int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
            while (issend.get(Thread.currentThread().getId()) != null) {
                if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                    addrindex = Appdevice.getAddrmin();
                cstr = String.format(Appdevice.getCmd(), String.format("%02X", addrindex));
                try {
                    Send(cstr);
                } catch (Exception EX) {
                     setText(EX.toString());
                }
                setText("向" + Appdevice.getName() + "设备发送指令" + cstr);
                reSend[addrindex]++;
                if (reSend[addrindex] > 3) {
                ${tableClass.shortClassName?uncap_first}ServiceImpl.UpdateStatus(ad, addrindex,1);
                reSend[addrindex] = 0;
                addrindex++;
                }
                Thread.sleep(timersp);
                Thread.sleep(timersp);
            }
        }

        @Async("threadPool")
        public void startReceiveThread(){
            isrecv.put(Thread.currentThread().getId(), true);
            while (isrecv.get(Thread.currentThread().getId()) != null) {
                //这里根据实际协议替换,解析方法recvCrc16;recvSum();
                recv();
                try {
                    Thread.sleep(interval);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
}
